package com.atguigu.spzx.manager.service.system.impl;

import cn.hutool.core.date.DateTime;
import com.atguigu.spzx.manager.service.system.FileUploadService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
 * @author Mahone
 */
@Service
public class FileUploadServiceImpl implements FileUploadService {
    @Override
    public String fileUpload(MultipartFile multipartFile) {
        // 用户传输对象的客户端
        MinioClient minioClient = MinioClient.builder()
                //minio的链接地址
                .endpoint("http://192.168.200.111:9001")
                .credentials("admin","cwc137189326")
                .build();

        try {
            // 上传文件
            InputStream inputStream = multipartFile.getInputStream();
            // 得到文件后缀
            String originalFilename = multipartFile.getOriginalFilename();
            String filenameExtension = StringUtils.getFilenameExtension(originalFilename);
            String objectName = "avatar" + new DateTime().toString("yyyy/MM/dd")
                    + UUID.randomUUID().toString().replace("-","") + "." + filenameExtension;
            minioClient.putObject(PutObjectArgs.builder().bucket("spzx-0911")
                    .object(objectName).stream(inputStream,inputStream.available(),-1).build());

            // 拼接返回url
            String url = "http://192.168.200.111:9001/" + "spzx-0911" + "/" + objectName;
            return url;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ServerException e) {
            throw new RuntimeException(e);
        } catch (InsufficientDataException e) {
            throw new RuntimeException(e);
        } catch (ErrorResponseException e) {
            throw new RuntimeException(e);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        } catch (InvalidResponseException e) {
            throw new RuntimeException(e);
        } catch (XmlParserException e) {
            throw new RuntimeException(e);
        } catch (InternalException e) {
            throw new RuntimeException(e);
        }


    }
}
